from sklearn.linear_model import LinearRegression, SGDRegressor
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error
import pandas as pd


def mylinearregression():
    # 1. 读取数据集
    df = pd.read_csv("../data/house_data.csv")
    # 2. 查看数据集
    # df.info()
    # print(df.shape)
    # 3.特征和目标值
    X = df.iloc[:, :-1]
    # 目标
    y = df[["MEDV"]]
    # 4.拆分训练集
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.33, random_state=42)
    # 5.特征工程--标准化
    # 特征做标准化
    std_x = StandardScaler()
    x_train = std_x.fit_transform(X_train)
    x_test = std_x.transform(X_test)
    # 目标值做标准化
    std_y = StandardScaler()
    y_train = std_y.fit_transform(y_train)
    y_test = std_y.transform(y_test)
    # 6.正规方程--->训练模型
    lr = LinearRegression()
    lr.fit(x_train, y_train)
    print(lr.coef_)
    print(lr.intercept_)
    # 7.预测
    y_pred = lr.predict(x_test)
    print(y_pred)
    # 8.模型评估
    result = mean_squared_error(y_test, y_pred)
    print("正规方程的均方误差{}".format(result))


def mylinearregression1():
    # 1. 读取数据集
    df = pd.read_csv("../data/house_data.csv")
    # 2. 查看数据集
    # df.info()
    # print(df.shape)
    # 3.特征和目标值
    X = df.iloc[:, :-1]
    y = df[["MEDV"]]
    # 4.拆分训练集
    X_train, X_test, y_train, y_test = train_test_split(
        X, y, test_size=0.33, random_state=42)
    # 5.特征工程--标准化
    # 特征做标准化
    std_x = StandardScaler()
    x_train = std_x.fit_transform(X_train)
    x_test = std_x.transform(X_test)
    # 目标值做标准化
    # std_y = StandardScaler()
    # y_train = std_y.fit_transform(y_train)
    # y_test = std_y.transform(y_test)
    # 6.正规方程--->训练模型
    lr = SGDRegressor(max_iter=10000, eta0=0.02)
    lr.fit(x_train, y_train)
    print(lr.coef_)
    print(lr.intercept_)
    # 7.预测
    y_pred = lr.predict(x_test)
    print(y_pred)
    # 8.模型评估
    result = mean_squared_error(y_test, y_pred)
    print("梯度下降的均方误差{}".format(result))

if __name__ == '__main__':
    mylinearregression()
    mylinearregression1()
